from tkinter import *
from tkinter.ttk import *
from view.commonmodels import *
from view.filetool import *
from PIL import Image, ImageTk
import time
import threading
import os

from model import *

class SFS_Set(Frame):
    def __init__(self, root,insertfunc,gettxlist):
        super().__init__(root)
        self.GalleryTool = GalleryTool()
        self.GalleryTool.load('相册规则.txt')

        self.txsta = False
        self.txingsta = False

        self.download_process = threading.Thread(name='下载图片',target=self.downloadPIC)

        self.COM = StringVar(self)
        self.serial = None
        self.insertfuc = insertfunc
        self.gettxlist = gettxlist

        self.serialControl = Frame(self)
        self.txsta_Label = StringVar(self.serialControl)
        self.txsta_Label.set("状态：不可下载")
        self.txsta_Button = StringVar(self.serialControl)
        self.txsta_Button.set("启动")

        Label(self.serialControl, textvariable=self.txsta_Label, width=12).grid(row=0, column=0, padx=2, pady=3)
        Button(self.serialControl, textvariable=self.txsta_Button,width=6,command=self.txsta_Set).grid(row=0,column=1,padx=2,pady=3)
        Button(self.serialControl, text="START",width=8,command=self.startTXCMD).grid(row=0,column=2,pady=3)

        self.serialChooser = Frame(self)
        self.serialChooserBox = Combobox(self.serialChooser, textvariable=self.COM, width=9)
        self.serialChooserButton = Button(self.serialChooser,text='扫面串口',width=10,command=self.scanSerialButtonCMD)

        self.serialChooserButton.grid(row=0,column=2)
        self.serialChooserBox.grid(row=0,column=1)
        Label(self.serialChooser, text="选择串口").grid(row=0,column=0)

        self.galleryChooser = Frame(self)
        self.galleryvar = StringVar(self.galleryChooser)
        self.galleryLabel = Label(self.galleryChooser,text='选择相册')
        self.galleryBox = Combobox(self.galleryChooser,values=list(self.GalleryTool.AlbumDict.keys()),textvariable=self.galleryvar)

        self.galleryBox.bind('<<ComboboxSelected>>', self.resetPiclist)

        self.galleryLabel.grid(row=0,column=0,pady=3)
        self.galleryBox.grid(row=0,column=1,pady=3)

        self.photoChooser = Frame(self)
        self.photovar = StringVar(self.photoChooser)
        self.photoChooserLabel = Label(self.photoChooser,text='目标图片')
        self.photoChooserBox = Combobox(self.photoChooser,values=[],textvariable=self.photovar)

        self.photoChooserLabel.grid(row=0,column=0)
        self.photoChooserBox.grid(row=0,column=1)

        self.serialChooser.pack()
        self.serialControl.pack()
        self.galleryChooser.pack()
        self.photoChooser.pack()

    def resetPiclist(self,*args):
        self.photoChooserBox['value'] = self.GalleryTool.returnPicList(self.galleryvar.get())

    def scanSerialButtonCMD(self):
        if not self.txingsta:
            self.serialChooserBox['values']=scanSerial()
            self.serialChooserBox.set('')
        pass

    def startTX(self):
        if self.COM.get() != '' and type(self.COM.get()) == str:
            self.serial = serialFlashLoader(self.COM.get(),115200,printf=self.insertfuc)
            self.insertfuc(self.serial.send_u8str(b'@  5=1#\r\n'))
            self.txsta_Label.set('状态：可以下载')
            self.txsta_Button.set('终止')

    def endTX(self):
        if self.serial.__class__ == serialFlashLoader:
            self.insertfuc(self.serial.send_u8str(b'@  5=0#\r\n'))
            self.txsta_Label.set('状态：不可下载')
            self.txsta_Button.set('启动')
            self.serial = None

        pass
    def txsta_Set(self):
        if self.txingsta == False and self.txsta_Button.get() == '启动':
            self.startTX()

        elif self.txingsta == False and self.txsta_Button.get() == '终止':
            self.endTX()
    def startTXCMD(self):
        if self.txingsta:
            print("任务冲突！")
        else:
            if self.serial.__class__ == serialFlashLoader and self.txsta_Label.get() == '状态：可以下载':
                if self.galleryBox.get() != '':
                    if self.photoChooserBox.get() != '':
                        print(f"将图片更新到相册:{self.galleryBox.get()}的{self.photoChooserBox.get()}")
                        tx_target = ''
                        if self.galleryBox.get() == '个人信息':
                            tx_target = 'INFORMATION'
                        elif self.galleryBox.get() == '屏保':
                            tx_target = 'PINGBAO'
                        if tx_target != '':
                            tx_target = f"@  1={tx_target}_{self.photoChooserBox.get()}#\r\n"
                            self.insertfuc(self.serial.send_u8str(tx_target.encode()))
                            time.sleep(0.5)
                            self.insertfuc("正在下载图片，请等待......\n")
                            self.download_process.start()


                    else:
                        self.insertfuc("ERROR:请选择待更新的图片\n")
                        print("ERROR:请选择待更新的图片")
                else:
                    self.insertfuc("ERROR:请选择待下载相册\n")
                    print("ERROR:请选择待下载相册")

            else:
                self.insertfuc("ERROR:请选择串口并开启下载")
                print("ERROR:请选择串口并开启下载")

    def downloadPIC(self):
        self.txingsta = True
        time.sleep(0.5)
        self.download_process = threading.Thread(name='下载图片', target=self.downloadPIC)
        self.serial.sendAsciiList(self.gettxlist())
        self.txingsta = False
        pass


class PreviewImg(Frame):
    def __init__(self, root):
        super().__init__(root)
        # img = Image.new(mode = "RGB",size=(320,240),color=0xFFFFFF)
        # self.img = ImageTk.PhotoImage(img)
        # self.img_show = Label(self,image=self.img)

        self.img = Imgtool(img_path=None)
        self.tkimg = ImageTk.PhotoImage(self.img.image)
        self.img_show = Label(self,image=self.tkimg)

        self.img_folder = os.getcwd()

        self.label = Label(self,text="图片预览")

        self.picChooser = FileChooser(self,defaultextension='.*', filetypes=[('所有文件','.*'),],command=self.resetPreviewImg)

        self.label.pack()
        self.picChooser.pack(pady=10)
        self.img_show.pack()

    # def resetPreviewImg(self,new_img):
    #     self.img = ImageTk.PhotoImage(new_img)
    #     self.img_show = Label(self,image=self.img)
    #     self.img_show.pack()

    def resetPreviewImg(self,*args):
        text = self.picChooser.files[self.picChooser.filenames[0]]
        path = os.path.dirname(self.picChooser.files[self.picChooser.filenames[0]])
        self.picChooser.reset_initialdir(path)

        self.img_show.destroy()
        self.img = Imgtool(img_path=text)
        self.img.resizeTo_4_3()
        self.tkimg = ImageTk.PhotoImage(self.img.image)
        self.img_show = Label(self,image=self.tkimg)


        self.label.pack()
        self.picChooser.pack(pady=10)
        self.img_show.pack()

    def get_pic_pixellist(self):
        return self.img.toRGB565_LH_list()


class RX_TEXT(Frame):
    def __init__(self, root):
        super().__init__(root)
        Label(self,text="接收缓存",font=20).pack(pady=10)

        self.textShow = Frame(self)
        self.sb = Scrollbar(self.textShow)
        self.RXtext = Text(self.textShow,height=25,width=50,yscrollcommand=self.sb.set,state='disabled')
        self.RXtext.pack(side="left",fill="y")
        self.sb.config(command=self.RXtext.yview)
        self.sb.pack(side="right", fill="y")
        self.textShow.pack(pady=10)

        Button(self,text='清除缓存',command=self.clearBuf).pack(pady=10)

    def clearBuf(self):
        self.RXtext['state'] = 'normal'
        self.RXtext.delete(1.0, "end")
        self.RXtext['state'] = 'disabled'

    def insertBuf(self,rxstr: str):
        self.RXtext['state'] = 'normal'
        self.RXtext.insert("end", '\n'+str(rxstr))
        self.RXtext['state'] = 'disabled'
        self.RXtext.see(END)



class SFS_GUI:
    def __init__(self):
        self.root = Tk()
        self.root.geometry("750x500")
        self.root.title('图片下载助手')

        self.previewImg = PreviewImg(self.root)
        self.rxtext = RX_TEXT(self.root)
        self.sfs_set = SFS_Set(self.root,insertfunc=self.rxtext.insertBuf,gettxlist=self.previewImg.get_pic_pixellist)

        self.previewImg.grid(row=1,column=1,pady=5)
        self.sfs_set.grid(row=0,column=1,pady=5)
        self.rxtext.grid(row=0, column=0, rowspan=2, padx=25, pady=5)




if __name__ == "__main__":
    sfsgui = SFS_GUI()

    sfsgui.root.mainloop()
